<template>
	<view class="page-container">
		<view class="container">
			<view class="container-li">
				<view class="container-li-left">
					昵称
				</view>
				<view class="container-li-right">
					{{ userInfo && userInfo.nickName ? userInfo.nickName : '未知' }}
				</view>
			</view>

			<view class="container-li">
				<view class="container-li-left">
					身份证前4位
				</view>
				<view class="container-li-right-edit">
					<u--input placeholder="请输入身份证前4位" border="none" inputAlign="right" type="number" maxlength="4"
						color="rgba(255, 179, 39, 1)" v-model="queryParams.code" @input="handleIdCardInput"
						@change="changeIdCardValue(queryParams.code)" @blur="isClickCity = false"
						:placeholderStyle="placeholderStyle" class="custom-input">
					</u--input>
				</view>
			</view>

			<view class="container-li">
				<view class="container-li-left">
					联系方式
				</view>
				<view class="container-li-right-edit">
					<u--input placeholder="请输入联系方式" border="none" inputAlign="right" type="number" maxlength="11"
						color="rgba(255, 179, 39, 1)" v-model="queryParams.phone" @input="handlePhoneInput"
						@change="changePhone(queryParams.phone)" :placeholderStyle="placeholderStyle"
						class="custom-input">
					</u--input>
				</view>
			</view>

			<view class="container-li">
				<view class="container-li-left">
					身份证所在城市
				</view>
				<view class="container-li-right">
					{{ queryParams.domicile ? queryParams.domicile :'未知' }}
				</view>
			</view>

			<view class="container-li-bottom">
				<view class="container-li-bottom-top" @click="handleSelectCity()">
					<view class="container-li-left">
						常住地城市
					</view>
					<view class="container-li-right-icon">
						<view class="">
							{{ queryParams.permanent ? queryParams.permanent :'未知' }}
						</view>
						<view class="">
							<u-icon name="arrow-right" color="rgba(0, 0, 0, 1)" size="10"></u-icon>
						</view>
					</view>
				</view>
				<u-line v-show="isChangeCity"></u-line>
				<view class="container-li-bottom-bottom" v-show="isChangeCity">
					<view class="container-li-bottom-bottom-title">
						请提供常住地城市的相关凭证，例如居住证、近期消费 凭证、公交记录截图等。
					</view>
					<view class="container-li-bottom-bottom-upLoad">
						<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
							:maxCount="1">
							<image src="/static/upLoadPicture.png" mode="widthFix"
								style="width: 144rpx;height: 144rpx;"></image>
						</u-upload>
					</view>
				</view>
			</view>
		</view>

		<view class="footer-btn-wrapper" @click="handleEmit()">
			<view class="footer-btn">
				提交
			</view>
		</view>
	</view>
</template>

<script>
	import config from '@/config/index.js'

	import {
		getCityList,
		phoneLocation,
		getPerson
	} from '@/request/api.js';
	export default {
		data() {
			return {
				userInfo: {}, //缓存中的个人信息
				placeholderStyle: 'color:rgba(255, 179, 39, 1); font-size: 26rpx;',
				fileList1: [],
				queryParams: {
					imageList: [], //上传的图片数组
					code: '', //身份证前四位
					phone: '', //联系方式
					domicile: '', //身份证所在城市
					permanent: '' //常住地所在城市
				},
				isChangeCity: false //是否更改过常住地城市
			};
		},
		onLoad(options) {
			this.userInfo = uni.getStorageSync('userInfo')
			// 接收传递过来的 userInfo 参数
			if (options.userInfo) {
				try {
					let currentPageInfo = JSON.parse(decodeURIComponent(options.userInfo));

					// 如果是已认证用户的信息，则填充表单
					if (currentPageInfo && currentPageInfo.starts !== undefined) {
						this.queryParams = {
							imageList: currentPageInfo.imgUrl ? [currentPageInfo.imgUrl] : [],
							code: currentPageInfo.code || '',
							phone: currentPageInfo.phone || '',
							domicile: currentPageInfo.domicile || '',
							permanent: currentPageInfo.permanent || '',
							id: currentPageInfo.id || '',
						}

						// 如果有图片URL，也需要更新fileList显示
						if (currentPageInfo.imgUrl) {
							this.fileList1 = [{
								url: currentPageInfo.imgUrl,
								status: "success"
							}];
						}
					}
				} catch (error) {
					console.error('解析用户信息失败:', error);
				}
			}
		},
		onShow() {
			uni.$on('citySelected', (cityInfo) => {
				let cityName = cityInfo.name;
				// 不再去除"市"字

				// 当选择的城市与当前常住地城市不同时
				if (this.queryParams.permanent != cityName) {
					this.queryParams.permanent = cityName;
					// 判断常住地城市是否与身份证所在地城市不同（保留完整的城市名称进行比较）
					let domicileCity = this.queryParams.domicile;
					// 不再去除"市"字
					this.isChangeCity = cityName != domicileCity;
				}

				uni.$off('citySelected');
			});
		},
		methods: {
			// 提交
			handleEmit() {
				// 表单验证
				const validationResult = this.validateForm();
				if (!validationResult.isValid) {
					uni.showToast({
						title: validationResult.message,
						icon: 'none'
					});
					return;
				}

				let params = {
					userId: this.$store.state.userInfo.userId,
					person: this.userInfo?.nickName || '',
					code: this.queryParams.code,
					phone: this.queryParams.phone,
					domicile: this.queryParams.domicile,
					permanent: this.queryParams.permanent,
					imgUrl: this.isChangeCity == true ? this.queryParams.imageList[0] : '',
					starts: 3
				}
				if (this.queryParams.id) {
					params.id = this.queryParams.id
				}

				// 显示加载提示
				uni.showLoading({
					title: '提交中...'
				});

				getPerson(params).then(res => {
					if (res.data.code == 200) {
						uni.showToast({
							title: '提交成功',
							icon: 'none'
						});

						// 延迟返回，让用户看到成功提示
						setTimeout(() => {
							uni.navigateBack();
						}, 1500);
					} else {
						uni.showToast({
							title: res.data.msg || '提交失败',
							icon: 'none'
						});
					}
				}).catch(error => {
					uni.showToast({
						title: '提交失败，请稍后重试',
						icon: 'none'
					});
					console.error('提交失败:', error);
				}).finally(() => {
					// 隐藏加载提示
					uni.hideLoading();
				});
			},

			// 需要输入联系方式后才跳转页面
			handleSelectCity() {
				uni.navigateTo({
					url: '/pages_sub/common/city/selectCity'
				})
			},
			// 表单验证方法
			validateForm() {
				// 验证身份证前4位
				if (!this.queryParams.code) {
					return {
						isValid: false,
						message: '请输入身份证前4位'
					};
				}

				if (this.queryParams.code.length !== 4) {
					return {
						isValid: false,
						message: '身份证前4位格式不正确'
					};
				}

				// 验证联系方式
				if (!this.queryParams.phone) {
					return {
						isValid: false,
						message: '请输入联系方式'
					};
				}

				if (this.queryParams.phone.length !== 11) {
					return {
						isValid: false,
						message: '手机号格式不正确'
					};
				}

				// 验证身份证所在城市
				if (!this.queryParams.domicile || this.queryParams.domicile.includes('错误')) {
					return {
						isValid: false,
						message: '请正确填写身份证前4位'
					};
				}

				// 验证常住地城市
				if (!this.queryParams.permanent || this.queryParams.permanent.includes('错误')) {
					return {
						isValid: false,
						message: '请正确填写手机号'
					};
				}

				// 如果更改过常住地城市
				if (this.isChangeCity == true) {
					// 验证图片上传
					if (!this.queryParams.imageList || this.queryParams.imageList.length === 0) {
						return {
							isValid: false,
							message: '请上传凭证图片'
						};
					}
				}


				return {
					isValid: true,
					message: ''
				};
			},
			// 监听身份证输入框的值发生变化去请求获取所在地
			changeIdCardValue(val) {
				if (val.length == 4) {
					this.getCurrentCity(val)
				}
			},
			// 监听手机号输入框的值变化去请求获取归属地
			changePhone(val) {
				if (val.length == 11) {
					this.getPlaceoforigin(val)
				}
			},
			// 根据身份证前四位获取所在城市
			getCurrentCity(val) {
				let params = {
					regionId: val + '00'
				}
				getCityList(params).then(res => {
					if (res.data.rows && res.data.rows.length > 0) {
						if (res.data.rows[0].regionName && res.data.rows[0].regionName.trim() !== '') {
							this.queryParams.domicile = this.formatAddress(res.data.rows[0].mergerName)
						} else {
							this.queryParams.domicile = '身份证前4位填写错误'
						}
					} else {
						this.queryParams.domicile = '身份证前4位填写错误'
					}
				}).catch(error => {
					// 请求失败处理
					console.error('身份证城市查询失败:', error);
					this.queryParams.domicile = '查询失败，请稍后重试';
				})
			},
			formatAddress(address) {
				if (!address) return ''

				const parts = address.split(',')
				const filteredParts = parts.filter(part => part && part !== '中国')

				// 处理每个部分：移除"省"字
				const processedParts = filteredParts.map(part => {
					return part.replace('省', '')
				})

				return processedParts.join('·')
			},
			// formatAddress(address) {
			// 	if (!address) return ''

			// 	const parts = address.split(',')
			// 	// 移除"中国"部分（如果存在），并过滤空值
			// 	const filteredParts = parts.filter(part => part && part !== '中国')

			// 	return filteredParts.join('·')
			// },

			// 根据手机号获取归属地
			getPlaceoforigin(val) {
				let params = {
					phone: val,
					url: 'https://sjlocation.market.alicloudapi.com/phoneLocation',
					appCode: '72f51f61e8c543d4ad83e4b943adf107'
				}
				phoneLocation(params).then(res => {
					if (res.data.code == 200 && res.data.rows) {
						// 增加对空字符串的判断
						if (res.data.rows.trim() !== '') {
							this.queryParams.permanent = res.data.rows
						} else {
							this.queryParams.permanent = '手机号格式错误'
						}
					} else {
						this.queryParams.permanent = '手机号格式错误'
					}
				}).catch(error => {
					// 请求失败处理
					console.error('手机号归属地查询失败:', error);
					this.queryParams.permanent = '查询失败，请稍后重试';
				})
			},
			// 身份证号码输入处理
			handleIdCardInput(value) {
				// 额外的输入处理，确保数据一致性
				const numericValue = value.replace(/\D/g, '');
				this._idCardValue = numericValue.slice(0, 6);
			},

			// 手机号码输入处理
			handlePhoneInput(value) {
				// 额外的输入处理，确保数据一致性
				const numericValue = value.replace(/\D/g, '');
				this._phoneValue = numericValue.slice(0, 11);
			},

			// 删除图片
			deletePic(event) {
				const deleteFile = event.file
				if (deleteFile && deleteFile.url) {
					const urlIndex = this.queryParams.imageList.indexOf(deleteFile.url);
					if (urlIndex > -1) {
						this.queryParams.imageList.splice(urlIndex, 1);
					}
				}
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this[`fileList${event.name}`].length;

				// 先添加到文件列表，设置为上传中状态
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: "uploading",
						message: "上传中",
					});
				});

				for (let i = 0; i < lists.length; i++) {
					try {
						const result = await this.uploadFilePromise(lists[i].url);
						let item = this[`fileList${event.name}`][fileListLen];
						this[`fileList${event.name}`].splice(
							fileListLen,
							1,
							Object.assign(item, {
								status: "success",
								message: "",
								url: result,
							})
						);
					} catch (error) {
						// 上传失败时更新文件状态
						let item = this[`fileList${event.name}`][fileListLen];
						this[`fileList${event.name}`].splice(
							fileListLen,
							1,
						);
						// 同时显示错误提示
						uni.showToast({
							title: error.message || '上传失败',
							icon: 'none'
						});
					}
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				let _that = this
				const base_url = config.baseURL
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: base_url + '/qnyUpload/upload',
						filePath: url,
						name: "file",
						header: {
							'Authorization': uni.getStorageSync('token') || '',
							'Accept': 'application/json'
						},
						success: (res) => {
							console.log(res);
							// 检查HTTP状态码
							if (res.statusCode === 413) {
								reject(new Error('图片过大，请选择较小的图片'));
								return;
							}

							// 检查其他错误状态码
							if (res.statusCode !== 200) {
								reject(new Error(`上传失败，状态码：${res.statusCode}`));
								return;
							}

							try {
								// 解析服务器返回的数据
								const responseData = typeof res.data === 'string' ? JSON.parse(res
									.data) : res.data;

								// 检查响应状态
								if (responseData.code === 200) {
									// 成功获取网络地址
									const imageUrl = responseData.url;
									// 将图片URL添加到imageList数组中
									if (imageUrl) {
										this.queryParams.imageList.push(imageUrl);
									}
									resolve(imageUrl);
								} else {
									// 业务逻辑错误
									console.error('上传失败:', e);
									reject(new Error(responseData.msg || '上传失败'));
								}
							} catch (error) {
								// 解析失败
								console.error('响应数据解析失败:', error);
								reject(new Error('服务器响应格式错误'));
							}
						},
						fail: (err) => {
							// 网络请求失败
							// 根据错误类型提供更具体的错误信息
							if (err.errMsg && err.errMsg.includes('request:fail')) {
								reject(new Error('网络连接失败，请检查网络设置'));
							} else {
								reject(new Error('网络请求失败'));
							}
						}
					});
				});
			}
			// uploadFilePromise(url) {
			// 	const base_url = config.baseURL
			// 	return new Promise((resolve, reject) => {
			// 		let a = uni.uploadFile({
			// 			url: base_url + '/qnyUpload/upload', // 仅为示例，非真实的接口地址
			// 			filePath: url,
			// 			name: "file",
			// 			header: {
			// 				'Authorization': uni.getStorageSync('token') || '', // 添加认证token
			// 				'Accept': 'application/json'
			// 			},
			// 			success: (res) => {
			// 				setTimeout(() => {
			// 					resolve(res.data.data);
			// 				}, 1000);
			// 			},
			// 		});
			// 	});
			// },
		}
	};
</script>
<style>
	page {
		background-color: rgba(248, 248, 248, 1) !important;
	}
</style>
<style lang="scss" scoped>
	.page-container {
		height: 100vh;

		.container {
			.container-li-bottom {
				background-color: rgba(255, 255, 255, 1);
				box-shadow: rgba(153, 153, 153, 0.2);
				margin: 30rpx;
				border-radius: 20rpx;
				padding: 0 30rpx;

				.container-li-bottom-top {
					display: flex;
					justify-content: space-between;
					align-items: center;
					height: 100rpx;

					.container-li-left {
						width: 50%;
						color: rgba(0, 0, 0, 1);
						font-weight: bold;
						font-size: 30rpx;
					}

					.container-li-right-icon {
						color: rgba(255, 179, 39, 1);
						font-weight: 400;
						font-size: 26rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						height: 100%;

						.text-content {
							flex: 1;
							text-align: right;
							margin-right: 10rpx;
						}

						.icon-content {
							display: flex;
							align-items: center;
							justify-content: flex-end;
						}
					}
				}

				.container-li-bottom-bottom {
					margin-top: 30rpx;

					.container-li-bottom-bottom-title {
						color: rgba(120, 120, 130, 1);
						font-size: 26rpx;
						line-height: 40rpx;
						padding-bottom: 30rpx;
					}

					.container-li-bottom-bottom-upLoad {
						padding-bottom: 30rpx;
					}
				}
			}

			.container-li {
				background-color: rgba(255, 255, 255, 1);
				box-shadow: rgba(153, 153, 153, 0.2);
				margin: 30rpx;
				border-radius: 20rpx;
				padding: 0 30rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 100rpx;

				.container-li-left {
					width: 50%;
					color: rgba(0, 0, 0, 1);
					font-weight: bold;
					font-size: 30rpx;
				}

				.container-li-right {
					color: rgba(77, 77, 86, 1);
					font-weight: 400;
					font-size: 26rpx;
				}




				.container-li-right-edit {
					color: rgba(255, 179, 39, 1);
					font-weight: 400;
					font-size: 26rpx;
					display: flex;
					align-items: center;
					height: 100%;
					flex: 1;
				}

				.custom-input {
					font-size: 26rpx;
					color: rgba(255, 179, 39, 1);
					flex: 1;
					text-align: right;
				}
			}
		}

		/* 底部按钮固定容器 */
		.footer-btn-wrapper {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			display: flex;
			justify-content: center;
			padding: 20rpx 0 50rpx;
			background: linear-gradient(to bottom, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1));

			/* 渐变背景 */

			.footer-btn {
				background-color: rgba(255, 179, 39, 1);
				font-weight: 900;
				font-size: 36rpx;
				line-height: 36rpx;
				padding: 30rpx 36rpx;
				text-align: center;
				width: 570rpx;
				border-radius: 40rpx;
				color: rgba(0, 0, 0, 1);
				box-shadow: 0 8rpx 20rpx rgba(255, 179, 39, 0.3);
			}
		}
	}
</style>